package top.korori.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.korori.common.bo.MediaPicFormBo;
import top.korori.common.enums.IsDel;
import top.korori.common.exception.BizException;
import top.korori.entity.SvUser;
import top.korori.entity.SvUserArea;
import top.korori.entity.req.SvUserEditReq;
import top.korori.entity.res.SvEditUserInfoRes;
import top.korori.entity.res.SvMediaRes;
import top.korori.entity.res.SvUserAreaTreeRes;
import top.korori.entity.res.SvUserInfoRes;
import top.korori.enums.SvMediaSourceEnum;
import top.korori.enums.SvMediaUseEnum;
import top.korori.mapper.SvUserMapper;
import top.korori.service.ISvMediaService;
import top.korori.service.ISvUserAreaService;
import top.korori.service.ISvUserService;
import top.korori.uitls.SvSecurityUtil;

import java.sql.Date;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static top.korori.uitls.SvSecurityUtil.getUserId;

/**
 *
 * 短视频前台用户 服务实现类
 *
 * @author korori
 */
@Service
public class SvUserServiceImpl extends ServiceImpl<SvUserMapper, SvUser> implements ISvUserService {


    @Autowired
    private ISvUserAreaService svUserAreaService;

    @Autowired
    private ISvMediaService svMediaService;


    @Override
    public SvUser getByAccount(String account) {
        return this.lambdaQuery()
                .eq(Validator.isEmail(account), SvUser::getEmail, account)
                .eq(Validator.isMobile(account), SvUser::getPhone, account)
                .eq(SvUser::getIsDel,IsDel.NORMAL)
                .one();
    }


    @Override
    public SvUser getUserInfo() {
        return this.getById(SvSecurityUtil.getUserId());
    }

    @Override
    public SvUser getByPhone(String phone) {
        return this.lambdaQuery().eq(SvUser::getPhone,phone).eq(SvUser::getIsDel, IsDel.NORMAL).one();
    }

    @Override
    public SvUser getByEmail(String email) {
        return this.lambdaQuery().eq(SvUser::getEmail,email).eq(SvUser::getDesc,IsDel.NORMAL).one();
    }

    @Override
    public SvUser getByUserName(String userName) {
        return this.lambdaQuery().eq(SvUser::getUserName,userName).one();
    }

    @Override
    public void editInfo(SvUserEditReq svUserEditReq) {
        Long userId = getUserId();
        SvUser dbSvUser = this.getByUserName(svUserEditReq.getUserName());
        if (ObjUtil.isNotNull(dbSvUser) && ObjUtil.notEqual(dbSvUser.getUserId(),userId)){
            BizException.cast("该用户已经存在");
        }

        LambdaUpdateWrapper<SvUser> updateWrapper = new LambdaUpdateWrapper<>();



        updateWrapper.eq(SvUser::getUserId,userId);

        //修改昵称
        updateWrapper.set(ObjUtil.isNotNull(svUserEditReq.getUserName()),SvUser::getUserName, svUserEditReq.getUserName());

        //修改性别
        updateWrapper.set(ObjUtil.isNotNull(svUserEditReq.getSex()),SvUser::getSex, svUserEditReq.getSex());

        //修改生日
        LocalDate birthday = svUserEditReq.getBirthday();
        if (ObjUtil.isNotNull(birthday)){
            LocalDate startDate = LocalDate.of(1900, 1, 1);
            LocalDate lastDate = LocalDate.now();
            if (birthday.isBefore(startDate) || birthday.isAfter(lastDate)){
                BizException.cast("非法生日");
            }
        }

        updateWrapper.set(ObjUtil.isNotNull(birthday),SvUser::getBirthday,birthday);

        //修改描述
        updateWrapper.set(ObjUtil.isNotNull(svUserEditReq.getDesc()),SvUser::getDesc, svUserEditReq.getDesc());


        //修改所在地
        List<Integer> localIds = svUserEditReq.getLocalId();


        if (ObjUtil.isEmpty(localIds)){
            updateWrapper.set(ObjUtil.isNotNull(localIds),SvUser::getLocalId,"");
        } else {
            Boolean existArea = svUserAreaService.isExistArea(localIds.get(0), localIds.get(1));
            if (!existArea){
                BizException.cast("非法地区");
            }

            String strIds = localIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            updateWrapper.set(SvUser::getLocalId,strIds);
        }

        this.update(updateWrapper);

    }

    @Override
    public SvMediaRes uploadAvatar(String base64) {
        MediaPicFormBo mediaPicFormBo = new MediaPicFormBo();
        mediaPicFormBo.setBase64(base64);
        mediaPicFormBo.setUse(SvMediaUseEnum.SV_AVATAR.getUse());
        SvMediaRes svMediaRes = svMediaService.uploadBase64Pic(mediaPicFormBo, SvMediaSourceEnum.FRONT.getSource());
        this.lambdaUpdate().eq(SvUser::getUserId,SvSecurityUtil.getUserId()).set(SvUser::getAvatar, svMediaRes.getUrl()).update();
        return svMediaRes;
    }

    @Override
    public SvUserInfoRes getLoginInfo() {

        SvUserInfoRes svUserInfoRes = baseMapper.getUserExtInfo(SvSecurityUtil.getUserId());

        String localIds = svUserInfoRes.getLocalId();

        List<SvUserArea> svUserAreas = localIdToAreaList(localIds);
        svUserInfoRes.setLocalArea(svUserAreas);


        if (ObjUtil.isNotEmpty(svUserInfoRes.getBirthday())){

            String zodiac = DateUtil.getZodiac(svUserInfoRes.getBirthday().getMonthValue() - 1, svUserInfoRes.getBirthday().getDayOfMonth());
            int age = DateUtil.ageOfNow(Date.valueOf(svUserInfoRes.getBirthday()));

            svUserInfoRes.setZodiac(zodiac);
            svUserInfoRes.setAge(age);
        }
        return svUserInfoRes;

    }

    @Override
    public SvEditUserInfoRes getEditInfo() {
        SvUser userInfo = this.getUserInfo();
        SvEditUserInfoRes svEditUserInfoRes = BeanUtil.copyProperties(userInfo, SvEditUserInfoRes.class);
        svEditUserInfoRes.setZodiac(DateUtil.getZodiac(svEditUserInfoRes.getBirthday().getMonthValue(), svEditUserInfoRes.getBirthday().getDayOfMonth()));
        svEditUserInfoRes.setAge(DateUtil.ageOfNow(Date.valueOf(svEditUserInfoRes.getBirthday())));
        svEditUserInfoRes.setLocalArea(localIdToAreaList(userInfo.getLocalId()));
        return svEditUserInfoRes;
    }

    @Override
    public void uploadAvatarFile(MultipartFile multipartFile) {
        SvMediaRes svMediaRes = svMediaService.uploadPic(multipartFile, SvMediaUseEnum.SV_AVATAR.getUse(), SvMediaSourceEnum.FRONT.getSource());
        this.lambdaUpdate().eq(SvUser::getUserId,SvSecurityUtil.getUserId()).set(SvUser::getAvatar, svMediaRes.getUrl()).update();
    }

    /**
     * 地址id转城市数据
     * @return 城市数据
     */
    private List<SvUserArea> localIdToAreaList(String localIds){

        List<SvUserAreaTreeRes> tree = svUserAreaService.tree();

        String[] localIdArr = localIds.split(",");


        if (ObjUtil.isNotEmpty(localIds)) {

            List<SvUserAreaTreeRes> provinceAreaArr = provinceAreaArr = tree.stream()
                    .filter(item -> ObjUtil.equal(Integer.valueOf(localIdArr[0]), item.getAreaId()))
                    .collect(Collectors.toList());
            SvUserAreaTreeRes svUserAreaTreeRes = provinceAreaArr.get(0);
            List<SvUserAreaTreeRes> childrenArr = svUserAreaTreeRes.getChildren();
            List<SvUserAreaTreeRes> cityArr = childrenArr.stream()
                    .filter(item -> ObjUtil.equal(item.getAreaId(), Integer.valueOf(localIdArr[1])))
                    .collect(Collectors.toList());

            if (ObjUtil.isEmpty(cityArr) ||  ObjUtil.isEmpty(provinceAreaArr)){
              return new ArrayList<>();
            }

            List<SvUserArea> svUserAreas = new ArrayList<>();

            svUserAreas.add(BeanUtil.copyProperties(svUserAreaTreeRes,SvUserArea.class));
            svUserAreas.add(BeanUtil.copyProperties(cityArr.get(0),SvUserArea.class));
            return svUserAreas;

        }

        return new ArrayList<>();
    }
}
























